package com.sunlands.qdcy.tongzhuo.web;

import com.sunlands.qdcy.tongzhuo.common.annotation.AutoLog;
import com.sunlands.qdcy.tongzhuo.exception.SensitiveException;
import com.sunlands.qdcy.tongzhuo.feign.SocketClient;
import com.sunlands.qdcy.tongzhuo.model.DiaryDO;
import com.sunlands.qdcy.tongzhuo.model.UserDiaryForwardDO;
import com.sunlands.qdcy.tongzhuo.service.DiaryService;
import com.sunlands.qdcy.tongzhuo.service.ForwardService;
import com.sunlands.qdcy.tongzhuo.service.UserDiaryTopicService;
import com.sunlands.qdcy.tongzhuo.util.CompareStrSimUtil;
import com.sunlands.qdcy.tongzhuo.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

import static com.sunlands.qdcy.tongzhuo.constant.CommonResultMessage.CON_SENSITIVE;
import static com.sunlands.qdcy.tongzhuo.constant.CommonResultMessage.SIMILARITY_RATIO_LIMIT;
import static com.sunlands.qdcy.tongzhuo.vo.BusinessResult.createInstance;
import static com.sunlands.qdcy.tongzhuo.web.DiaryController.SIMILARITY_RATIO;
import static com.sunlands.qdcy.tongzhuo.web.DiaryController.SIMILARITY_RATIO_COUNT;

/**
 * Created with meng.
 * User: meng5
 * Date: 2019-06-25
 * Description:
 */
@Slf4j
@Api(tags = "2、转发相关")
@RestController
@RequestMapping("/user/forward")
public class ForwardController extends BaseController {
    @Autowired
    private ForwardService forwardService;
    @Autowired
    private UserDiaryTopicService topicService;
    @Autowired
    private SocketClient socketClient;
    @Autowired
    private DiaryService diaryService;

    @AutoLog
    @ApiOperation(value = "[app]转发时记录")
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/record")
    public BusinessResult record(@RequestBody ForwardVO vo) {

        //如果没传fromUserId，则取当前登录用户
        if (vo.getFromUserId() == null) {
            vo.setFromUserId(currentUserId());
        }

        if (vo == null) {
            throw new IllegalArgumentException("参数对象不能为空！");
        }
        if (vo.getType() == null) {
            throw new IllegalArgumentException("转发类型不能为空！");
        }
        if (UserDiaryForwardDO.ForwardType.create(vo.getType()) == null) {
            throw new IllegalArgumentException("非法的类型参数！");
        }
        if (vo.getTargetId() == null || vo.getTargetId() == 0) {
            throw new IllegalArgumentException("被转发对象id不能为空！");
        }
        if (vo.getTargetUserId() == null) {
            throw new IllegalArgumentException("被转发用户id不能为空！");
        }

        forwardService.addForward(vo);


        return BusinessResult.createSuccessInstance(null);
    }


    @AutoLog
    @ApiOperation(value = "[app]转发到我的日记")
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/diary/publish")
    public BusinessResult forwardToMine(@RequestBody ForwardDiaryVO diaryVO) {

        Long userId = currentUserId();
        //敏感词校验
        BusinessResult checkContent = socketClient.checkContent(CheckVO.builder().content(diaryVO.getContent()).build());
        if (checkContent.getCode().equals(CON_SENSITIVE.code)) {
            throw new SensitiveException("转发内容： " + diaryVO.getContent() + "\n敏感词：" + checkContent.getMessage());
        }

        List<DiaryDO> lately1HourDiary = diaryService.findLately1HourDiary(currentUserId());

        if (lately1HourDiary.size() >= 10) {
            return createInstance(SIMILARITY_RATIO_LIMIT.code, "您已连续发表多次内容，请稍后再试吧~");
        }
        //转发相同的日记次数超出
        if (lately1HourDiary.stream()
                .filter(exist -> DiaryDO.CreateTypeEnums.FORWARD.type.equals(exist.getCreateType())
                        && exist.getRootId().equals(diaryVO.getRootId())).count() > SIMILARITY_RATIO_COUNT) {
             return createInstance(SIMILARITY_RATIO_LIMIT);
        }


        //大于30字的日记检测重复发布次数
        if (diaryVO.getContent().length() > 30) {
            if (lately1HourDiary.stream().filter(exist ->
                    CompareStrSimUtil.getSimilarityRatio(exist.getContent(), diaryVO.getContent(), true) > SIMILARITY_RATIO)
                    .count() >= SIMILARITY_RATIO_COUNT) {
                return createInstance(SIMILARITY_RATIO_LIMIT);
            }
        }


        DiaryDO newDiary = forwardService.saveForwardDiary(diaryVO, userId);
        if (Objects.nonNull(newDiary.getTopicId())) {
            topicService.modifyTopicHot("0", newDiary.getTopicId());
        }

        return BusinessResult.createSuccessInstance(newDiary);
    }

    @AutoLog
    @ApiOperation(value = "[app]我收到的转发记录-消息中二级页面")
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/page")
    public BusinessResult<Page<ForwardMessageVO>> userForwardList(@ApiParam(value = "用户id", required = false) @RequestParam(required = false) Long userId,
                                                                  @ApiParam(value = "页码", required = true) @RequestParam(defaultValue = "1") Integer page,
                                                                  @ApiParam(value = "页码大小", required = true) @RequestParam(defaultValue = "4") Integer size) {

        Long currentUserId = this.currentUserId();
        if (currentUserId == null) {
            currentUserId = userId;
        }

        Page<ForwardMessageVO> result = forwardService.msgPage(currentUserId, page, size);
        return BusinessResult.createSuccessInstance(result);
    }


}